<script lang="ts" setup>
import type { FieldRule, FormInstance } from '@arco-design/web-vue'
import type { AreaItem } from '@/apis/model/resolve'
import { Message } from '@arco-design/web-vue'
// import { getApplicationsApi } from '@/apis/modules/application.ts'
import {
  addDnsDomainApi,
  getDnsAccountListApi,
  getDnsProviderListApi,
  updateDnsDomainApi,
} from '@/apis/modules/dns'

interface IProp {
  record?: AreaItem
  appList?: LabelValue[]
}
const props = withDefaults(defineProps<IProp>(), {})
const emit = defineEmits<IEmits>()
interface IEmits {
  (e: 'reload', flag: boolean): void
}
const visible = defineModel<boolean>('visible', { required: true })
const title = computed(() => (props.record?.id ? '编辑域名' : '新建域名'))
const formRef = ref<FormInstance>()
const dnsNameOptions = ref<LabelValue[]>([])
const dnsDomainNameOptions = ref<LabelValue[]>([])
const formState = ref({
  app_id: '',
  name: '',
  remark: '',
  account_id: '',
  id: '',
})
const appList = computed<OptionItem[]>(() => {
  return useAppStore().appList || []
})
const rules: Record<string, FieldRule> = {
  account_id: { required: true, message: '请选择域名账号' },
  name: { required: true, message: '请选择域名' },
  app_id: { required: true, message: '请选择所属应用' },
}
const loading = ref(false)
async function getAccountList() {
  try {
    loading.value = true
    const res = await getDnsAccountListApi({ offset: 0, limit: 0 })
    loading.value = false
    dnsNameOptions.value = res.list
      .map(v => ({ label: v.name!, value: v.id!, type: v?.provider_type }))
      .filter(Boolean)
  } catch (e) {
    console.error(e)
    loading.value = false
  }
}
async function handleRefresh() {
  await getAccountList()

  const groupExists = dnsNameOptions.value.some(
    item => item.value === formState.value.account_id,
  )
  if (!groupExists) {
    formState.value.account_id = ''
  }

  Message.success('更新成功')
}
async function handleOpen() {
  await getAccountList()
  if (props.record) {
    formState.value.name = props.record.name
    formState.value.remark = props.record.remark
    formState.value.account_id = props.record.account_id
    formState.value.app_id = props.record.app_id
    formState.value.id = props.record.id
    getDnsProviderList()
  } else {
    dnsDomainNameOptions.value = []
  }
}
const accountData = ref()
async function getDnsProviderList(id?: string) {
  if (props.record?.id)
    return
  accountData.value = dnsNameOptions.value.filter(v => v.value === id)
  const res = await getDnsProviderListApi({
    account_id: formState.value.account_id,
  })

  const list = res.list ?? []
  dnsDomainNameOptions.value = list
    .map(item => ({ label: item.name!, is_added: item.is_added! }))
    .filter(Boolean)
}

function handleJump() {
  window.open('/sys/system-domains/domain-account?type=open', '_target')
}
async function handleSubmit() {
  const error = await formRef.value?.validate()
  if (error)
    return false
  const fn = props.record ? updateDnsDomainApi : addDnsDomainApi
  const data = props.record
    ? { id: props.record.id!, ...formState.value }
    : formState.value
  await fn(data).then(() => {
    Message.success('操作成功')
    visible.value = false
  })
}

function handleClose() {
  formRef.value?.resetFields()
  emit('reload', !!props.record?.id)
}
</script>

<template>
  <resource-dialog
    v-model:visible="visible"
    :title="title"
    :width="480"
    :mask-closable="false"
    :before-open="handleOpen"
    :before-ok="handleSubmit"
    :before-close="handleClose"
  >
    <a-form
      ref="formRef"
      layout="vertical"
      :rules="rules"
      :model="formState"
    >
      <a-form-item
        label="域名账号"
        field="account_id"
        asterisk-position="end"
      >
        <a-select
          v-model="formState.account_id"
          placeholder="请选择域名账号"
          :loading="loading"
          value-key="value"
          show-footer-on-empty
          not-found-content="请前往DNS 账户新建数据"
          @change="getDnsProviderList"
        >
          <template #label="{ data }">
            <section class="flex items-center gap-x-1">
              <i-icons-operate
                v-if="
                  getOptionsLabel(dnsNameOptions, data.value, 'type') === -1
                "
              />{{ data.label }}
            </section>
          </template>
          <template #footer>
            <div
              class="h-8 flex cursor-pointer items-center gap-x-1 px-3 text-[#00A65B] leading-8"
              @click="handleJump"
            >
              <span class="text-xs leading-[19px]">新建域名账号</span>
              <i-icons-jump size="14px" />
            </div>
          </template>
          <a-option
            v-for="item in dnsNameOptions"
            :key="item.value"
            :value="item.value"
          >
            <section class="flex items-center gap-x-1">
              <i-icons-operate v-if="item?.type === -1" />{{ item.label }}
            </section>
          </a-option>
        </a-select>
        <a-button
          class="ml-2 shrink-0 text-color-1"
          type="outline"
          @click="handleRefresh"
        >
          <template #icon>
            <i-icons-refresh />
          </template>
        </a-button>
      </a-form-item>
      <a-form-item
        v-if="!props.record?.id"
        label="域名"
        field="name"
        asterisk-position="end"
      >
        <a-select
          v-model="formState.name"
          placeholder="请选择域名"
          not-found-content="未获取到域名"
        >
          <a-option
            v-for="item in dnsDomainNameOptions"
            :key="item.label"
            :value="item.label"
            :disabled="item.is_added"
          >
            {{ item.label }} <span v-if="item.is_added"> （已添加） </span>
          </a-option>
        </a-select>
      </a-form-item>
      <a-form-item
        v-else
        label="域名"
        field="name"
        asterisk-position="end"
      >
        <a-input
          v-model="formState.name"
          class="disabled-input-value"
          placeholder="请输入域名"
          disabled
        />
      </a-form-item>
      <a-form-item
        label="所属应用"
        field="app_id"
        asterisk-position="end"
      >
        <a-select
          v-model="formState.app_id"
          :options="appList"
          :disabled="!!record?.id"
          placeholder="请选择所属应用"
          not-found-content="未获取到所属应用"
        />
      </a-form-item>

      <a-form-item
        label="备注"
        field="remark"
        asterisk-position="end"
      >
        <a-textarea
          v-model="formState.remark"
          :max-length="200"
          show-word-limit
          :auto-size="{ maxRows: 5, minRows: 5 }"
          placeholder="请输入备注"
        />
      </a-form-item>
    </a-form>
  </resource-dialog>
</template>

<style lang="less" scoped>
.disabled-input-value {
  background: var(--fill-1, #f7f8fa) !important;
}

:deep(.arco-input) {
  -webkit-text-fill-color: #1d2129;
}
</style>
